<?php

namespace app\task\cron;

use yunwuxin\cron\Task;
use think\facade\Db;
use app\admin\model\SmsSendList as SmsSendListModel;

/**
 * 短信通知
 */
class Sms extends Task
{
    /**
     * 每分钟执行
     */
    protected function configure()
    {
        // 分 时 日 月 周
        $this->expression = '* * * * *';
    }

    /**
     * 执行指令.
     */
    protected function handle()
    {
        echo '开始发送短信通知' . PHP_EOL;
        $lockKey = 'send_sms_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢' . PHP_EOL;

            return true;
        }

        cache($lockKey, 1, 500);

        // 供应商，代理商余额预警短信
        $aliyun = new \app\common\model\Sms;
        $list = Db::name('sms_log')
            ->field('id, params, mobile')
            ->where('status', 1)
            ->limit(60)
            ->select()
            ->toArray();
        foreach ($list as $v) {
            $res = $aliyun->send(json_decode($v['mobile'], true), json_decode($v['params'], true));
            Db::name('sms_log')
                ->where('id', $v['id'])
                ->update([
                    'result' => json_encode($res['result'], JSON_UNESCAPED_UNICODE),
                    'status' => $res['status'],
                ]);
        }
        unset($list);

        // 通道维护情况短信
//        $model = new SmsSendListModel();
//        $model->sendAllSms();

        cache($lockKey, null);
        echo '结束发送短信通知' . PHP_EOL;
    }
}
